package com.cmwa.solution.sys.msg.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cmwa.solution.base.controller.BaseController;
import com.cmwa.solution.base.entity.SearchParam;
import com.cmwa.solution.sys.msg.service.IMsgEmpConfService;
import com.cmwa.solution.sys.msg.service.IMsgConfService;
import com.cmwa.solution.sys.msg.vo.MsgConfVo;
import com.cmwa.solution.utils.SessionUtils;
import com.cmwa.solution.utils.cached.MsgBacklogCached;

@Controller
@RequestMapping("/msgBacklog")
public class MsgBacklogController extends BaseController{

	@Resource
	private IMsgConfService msgConfService;
	@Resource
	private IMsgEmpConfService msgEmpConfService;
	
	/**
	 * solution首页获取客户对应的待办信息
	 * @param sp
	 * @return
	 */
	@RequestMapping("/queryBacklog")
	@ResponseBody
	public List<MsgConfVo> queryBacklog(SearchParam sp){
		List<MsgConfVo> msgConfVosEmps = getBacklog(sp);//当前用户拥有的待办
		return msgConfVosEmps;
	}
	
	/**
	 * solution首页获取客户对应的待办信息(总数)
	 * @param sp
	 * @return
	 */
	@RequestMapping("/queryBacklogCount")
	@ResponseBody
	public String queryBacklogCount(SearchParam sp){
		List<MsgConfVo> msgConfVosEmps = getBacklog(sp);//当前用户拥有的待办
		if(msgConfVosEmps.size() > 0){
			int result = 0;
			for(int i =0;i<msgConfVosEmps.size();i++){
				result += Integer.parseInt(msgConfVosEmps.get(i).getBacklogOrMonitors());
			}
			return result+"";
		}
		return "0";
	}
	
	/**
	 * 查询待办
	 * @return
	 */
	List<MsgConfVo> getBacklog(SearchParam sp){
		String empId=SessionUtils.getEmployee().getID();
		
		List<MsgConfVo> msgConfVosEmps = new ArrayList<MsgConfVo>();//当前用户拥有的待办
		
		for(int i = 0; i < MsgBacklogCached.msgConfVoEmpRs.size();i++){//匹配出当前用户拥有的待办
			MsgConfVo vo = MsgBacklogCached.msgConfVoEmpRs.get(i);
			if(StringUtils.isNotBlank(vo.getMsgEmpConfRs())){
				if(vo.getMsgEmpConfRs().indexOf(empId)>-1){
					msgConfVosEmps.add(vo);
				}
			}
		}
		
		for(int i=0;i<msgConfVosEmps.size();i++){//根据用户拥有的待办去缓存里获取对应待办的数量
			String id=msgConfVosEmps.get(i).getId();
			if(MsgBacklogCached.dictCached.get(id) == null){//如果缓存里没有，则重新获取并放入缓存里
				MsgBacklogCached.getBacklog(msgConfVosEmps.get(i));
			}
			MsgConfVo vo=MsgBacklogCached.dictCached.get(id);
			msgConfVosEmps.get(i).setBacklogOrMonitors(vo.getBacklogOrMonitors());
		}
		return msgConfVosEmps;
	}
}
